import { ipcMain, IpcMainInvokeEvent } from 'electron'
import { PDFDocument, PDFPage } from 'pdf-lib'
import * as fs from 'fs/promises'
import * as path from 'path'
import type { Task } from '@/types'

interface PDFMergeOptions {
  reserveSpace: boolean
  margin: number
}

export function setupPDFHandlers() {
  // 处理PDF合并
  ipcMain.handle('pdf:merge', async (event: IpcMainInvokeEvent, files: string[], options: PDFMergeOptions) => {
    try {
      const mergedPdf = await PDFDocument.create()
      
      for (const file of files) {
        const pdfBytes = await fs.readFile(file)
        const pdf = await PDFDocument.load(pdfBytes)
        const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices())
        copiedPages.forEach((page: PDFPage) => {
          if (options.reserveSpace) {
            // 添加装订空间
            page.setSize(page.getWidth() + 20, page.getHeight())
          }
          mergedPdf.addPage(page)
        })
      }
      
      const pdfBytes = await mergedPdf.save()
      const outputPath = path.join(process.cwd(), 'output.pdf')
      await fs.writeFile(outputPath, pdfBytes)
      
      return { success: true, path: outputPath }
    } catch (error: any) {
      return { success: false, error: error.message }
    }
  })
} 